package com.itany.corejava.code09_集合.Map;

import java.util.*;

/**
 * @author 石小俊
 * 2024年07月25日 9:36
 */
public class Test02_遍历方式 {

    public static void main(String[] args) {
        Teacher teacher = new Teacher(1, "admin", 30);
        Teacher teacher2 = new Teacher(2, "jack", 31);
        Teacher teacher3 = new Teacher(3, "alice", 28);
        Teacher teacher4 = new Teacher(4, "lucy", 29);
        Map<Integer, Teacher> teachers = new HashMap<>();
        teachers.put(teacher.getId(), teacher);
        teachers.put(teacher2.getId(), teacher2);
        teachers.put(teacher3.getId(), teacher3);
        teachers.put(teacher4.getId(), teacher4);
        //test01(teachers);
        //test02(teachers);
        test03(teachers);
    }

    /**
     * 通过keySet方法获取key的Set集合,然后根据key获取到value
     * @param teachers
     */
    public static void test01(Map<Integer, Teacher> teachers) {
        Set<Integer> keys = teachers.keySet();
        for (Integer key : keys) {
            Teacher teacher = teachers.get(key);
            System.out.println("key:" + key + ",value:" + teacher);
        }
    }

    /**
     * 通过values方法获取value的Collection集合,该方式无法获取key
     * @param teachers
     */
    public static void test02(Map<Integer, Teacher> teachers) {
        Collection<Teacher> values = teachers.values();
        for (Teacher teacher : values) {
            System.out.println(teacher);
        }
    }

    /**
     * 通过entrySet获取所有key-value的集合
     * @param teachers
     */
    public static void test03(Map<Integer, Teacher> teachers) {
        Set<Map.Entry<Integer, Teacher>> entries = teachers.entrySet();
        Iterator<Map.Entry<Integer, Teacher>> it = entries.iterator();
        while (it.hasNext()) {
            // 取出当前迭代的Entry
            Map.Entry<Integer, Teacher> entry = it.next();
            Integer key = entry.getKey();
            Teacher teacher = entry.getValue();
            System.out.println("key:" + key + ",value:" + teacher);
        }
    }

}
